<template>
  <el-container style="min-height: 100vh">
    <!-- 侧边栏导航 -->
    <el-aside width="200px" class="sidebar">
      <div class="sidebar-logo">
        <h2>商家管理系统</h2>
      </div>
      <el-menu
        default-active="merchant/reconciliation"
        class="sidebar-menu"
        router
        :unique-opened="true"
      >
        <!-- 商家管理 -->
        <el-menu-item index="/merchant/manage">
          <span>商家管理</span>
        </el-menu-item>
        <!-- 餐品管理 -->
        <el-menu-item index="/merchant/dishes">
          <span>餐品管理</span>
        </el-menu-item>
        <!-- 对账申请（当前页） -->
        <el-menu-item index="/merchant/reconciliation">
          <span>对账申请</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <!-- 顶部导航栏（含退出按钮） -->
      <el-header class="header">
        <div class="header-title">对账申请</div>
        <el-button 
          type="default" 
          @click="handleLogout"
          class="logout-btn"
        >
          退出登录
        </el-button>
      </el-header>

      <el-main class="main-content">
        <div class="operation-bar">
          <el-button type="primary" @click="handleAdd">新增对账申请</el-button>
        </div>
        
        <el-table
          :data="reconciliationList"
          border
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column prop="id" label="对账ID" align="center" width="100" />
          <el-table-column prop="merchantName" label="商家名称" align="center" />
          <el-table-column prop="month" label="对账月份" align="center" width="150" />
          <el-table-column prop="amount" label="对账金额" align="center" width="120">
            <template #default="scope">{{ scope.row.amount.toFixed(2) }}</template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center" width="120">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 新增/编辑弹窗 -->
        <el-dialog
          v-model="isDialogOpen"
          :title="form.id ? '编辑对账申请' : '新增对账申请'"
          width="500px"
        >
          <el-form
            ref="formRef"
            :model="form"
            :rules="formRules"
            label-width="100px"
          >
            <el-form-item label="商家名称" prop="merchantName">
              <el-input v-model="form.merchantName" placeholder="请输入商家名称" />
            </el-form-item>
            <el-form-item label="对账月份" prop="month">
              <el-date-picker
                v-model="form.month"
                type="month"
                placeholder="选择对账月份"
                format="YYYY-MM"
                value-format="YYYY-MM"
              />
            </el-form-item>
            <el-form-item label="对账金额" prop="amount">
              <el-input v-model="form.amount" type="number" placeholder="请输入对账金额" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="待审核" value="待审核" />
                <el-option label="已通过" value="已通过" />
                <el-option label="已拒绝" value="已拒绝" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="isDialogOpen = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElTag } from 'element-plus';
import { useRouter } from 'vue-router';
import type { ElForm } from 'element-plus';

const router = useRouter();

// 定义对账申请类型
interface Reconciliation {
  id: number;
  merchantName: string;
  month: string;
  amount: number;
  status: '待审核' | '已通过' | '已拒绝';
}

// 对账列表数据
const reconciliationList = ref<Reconciliation[]>([]);
// 对话框状态
const isDialogOpen = ref(false);
// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();
// 表单数据
const form = reactive<Partial<Reconciliation>>({
  id: 0,
  merchantName: '',
  month: '',
  amount: 0,
  status: '待审核'
});

// 表单验证规则
const formRules = reactive({
  merchantName: [
    { required: true, trigger: 'blur', message: '请输入商家名称' }
  ],
  month: [
    { required: true, trigger: 'change', message: '请选择对账月份' }
  ],
  amount: [
    { required: true, trigger: 'blur', message: '请输入对账金额' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ],
  status: [
    { required: true, trigger: 'change', message: '请选择状态' }
  ]
});

// 页面加载时获取本地数据
onMounted(() => {
  // 模拟本地数据
  reconciliationList.value = [
    { id: 1, merchantName: '阳光餐厅', month: '2023-10', amount: 15600.50, status: '已通过' },
    { id: 2, merchantName: '学子餐厅', month: '2023-10', amount: 12800.30, status: '已通过' },
    { id: 3, merchantName: '清真餐厅', month: '2023-10', amount: 8900.75, status: '待审核' }
  ];
});

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case '待审核': return 'warning';
    case '已通过': return 'success';
    case '已拒绝': return 'danger';
    default: return 'info';
  }
};

// 打开新增对话框
const handleAdd = () => {
  formRef.value?.resetFields();
  Object.assign(form, { id: 0, merchantName: '', month: '', amount: 0, status: '待审核' });
  isDialogOpen.value = true;
};

// 打开编辑对话框
const handleEdit = (row: Reconciliation) => {
  Object.assign(form, { ...row });
  isDialogOpen.value = true;
};

// 提交表单
const handleSubmit = async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          // 编辑现有记录
          const index = reconciliationList.value.findIndex(r => r.id === form.id);
          if (index !== -1) {
            reconciliationList.value[index] = { ...reconciliationList.value[index], ...form } as Reconciliation;
          }
          ElMessage.success('编辑成功');
        } else {
          // 新增记录
          const newRecord = {
            ...form,
            id: Math.max(0, ...reconciliationList.value.map(r => r.id)) + 1
          } as Reconciliation;
          reconciliationList.value.push(newRecord);
          ElMessage.success('新增成功');
        }
        
        isDialogOpen.value = false;
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败');
      }
    }
  });
};

// 删除记录
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该对账记录吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    reconciliationList.value = reconciliationList.value.filter(r => r.id !== id);
    ElMessage.success('删除成功');
  } catch (error) {
    // 取消删除不处理
  }
};

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    });
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    router.push('/login');
    ElMessage.success('退出成功');
  } catch (error) {
    // 取消退出不处理
  }
};
</script>

<style scoped>
/* 侧边栏样式 */
.sidebar {
  background-color: #f5f7fa;
  border-right: 1px solid #e5e7eb;
}
.sidebar-logo {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #e5e7eb;
}
.sidebar-logo h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}
.sidebar-menu {
  margin-top: 10px;
}
.sidebar-menu .el-menu-item.is-active {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 顶部导航栏样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  border-bottom: 1px solid #e5e7eb;
  height: 60px;
}
.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.logout-btn {
  border-color: #ff4d4f;
  color: #ff4d4f;
}

/* 主内容区样式 */
.main-content {
  padding: 20px;
  background-color: #fff;
}
.operation-bar {
  margin-bottom: 10px;
}
</style>